/*
 * Project Name demo
 * File Name TestListener
 * Package Name com.huxiaosu.demo.socketio
 * Create Time 2023/1/29
 * Create by name：liujie
 */
package com.huxiaosu.demo.socketio.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.SocketIOClient;
import com.huxiaosu.demo.socketio.util.SocketCache;
import com.huxiaosu.demo.socketio.util.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.Lock;

/**
 * Description
 *
 * @ClassName: TestListener
 * @author: liujie
 * @date: 2023/1/29 10:17
 */
@Slf4j
public class TestListener implements MessageListener {
    @Autowired
    private RedisLockRegistry redisLockRegistry;
    @Override
    public void onMessage(Message message, byte[] channel) {
        if(redisLockRegistry == null){
            redisLockRegistry = SpringContextHolder.getBean(RedisLockRegistry.class);
        }
        Lock lock=redisLockRegistry.obtain("lock");
        lock.lock();
        try {
            byte[] body = message.getBody();
            String s = new String(body);
            log.info("str msg = {}",s);
            JSONObject jsonObject = JSONObject.parseObject(s);
            log.info("channel = {} msg = {}", new String(channel), jsonObject.toJSONString());
            SocketIOClient client = SocketCache.getInstance().getClient(jsonObject.getInteger("recipientAccountNo"));
            client.sendEvent(new String(channel), s);
            log.info("send success ...");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();

        }
    }
}